<script setup lang="ts">
import { createRoleUserAPI, getRoleDetailAPI, getTreeListAPI, updateRoleUserAPI } from '@/apis/system';
import type { RoleData, RoleParams } from '@/types/system';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
import type { TreeInstance } from 'element-plus/lib/components/index.js';
import { ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';

// 表单数据
const roleForm = ref<RoleParams>({
  roleName: '',
  remark: '',
  perms: []
})

// 表单校验
const roleFormRef = ref<FormInstance>()
const roleRules = ref<FormRules<RoleParams>>({
  roleName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  remark: [
    { required: true, message: '请输入角色描述', trigger: 'blur' },
  ]
})

// 当前激活的步骤
const activeStep = ref(1)

// 上一步
const prevStep = () => {
  activeStep.value--
}
// 下一步
const nextStep = async () => {
  try {
    if (activeStep.value === 1) {
      // 1. 校验表单1 - 常规表单
      await roleFormRef.value?.validate()
      // 表单校验没问题，进入下一步
      activeStep.value++
    } else if (activeStep.value === 2) {
      // 2. 校验表单2 - 树形节点选中
      roleForm.value.perms = [] // 先清空输入，避免 push 累加
      treeRefs.value.forEach(tree => {
        // 获取选中的节点，追加到数组中
        const res = tree.getCheckedKeys() as number[]
        roleForm.value.perms.push(res)
      })
      // 扁平化数组后，判断数组是否为空，如果空则提示用户
      if (roleForm.value.perms.flat().length === 0) {
        ElMessage.error('请至少勾选一项权限')
      } else {
        // 选中校验没问题，进入下一步（进入表单3）
        activeStep.value++
        // 进入表单3后，把选中的权限，同步到被禁用的树形组件
        diabledTreeRefs.value.forEach((tree, index)=>{
          tree.setCheckedKeys(roleForm.value.perms[index])
        })
      }
    }
  } catch {

  }
}

const router = useRouter()
// 确认添加
const onSubmit = async () => {
  // 获取角色 id
  const roleId = route.params.id
  // 有角色 id 为编辑修改，否则为添加
  if (roleId) {
    await updateRoleUserAPI({
      roleId: Number(roleId),
      ...roleForm.value
    })
  } else {
    // 发送表单给后端
    await createRoleUserAPI(roleForm.value)
  }
  // 轻提示
  ElMessage.success(roleId ? '更新成功' : '添加成功')
  // 返回上一页
  router.back()
}

// 获取权限列表(所有树形)
const treeList = ref<RoleData[]>([])
const getTreeList = async () => {
  const res = await getTreeListAPI()
  treeList.value = res.data
}
getTreeList()

// 可选择的树形组件（表单2）
const treeRefs = ref<TreeInstance[]>([])
// 被禁用选择的树形组件（表单3）
const diabledTreeRefs = ref<TreeInstance[]>([])

// 获取角色详情
const route = useRoute()
const getRoleDetail = async() => {
  if(route.params.id){
    const res = await  getRoleDetailAPI(Number(route.params.id))
    const { roleName, remark, perms } = res.data
    roleForm.value = { roleName, remark, perms }
  }
}
getRoleDetail()
</script>

<template>
  <div class="add-role">
    <header class="add-header">
      <el-page-header content="添加角色" @back="$router.back()" />
      
    </header>
    <main class="add-main">
      <div class="step-container">
        <el-steps direction="vertical" :active="activeStep">
          <el-step title="角色信息" />
          <el-step title="权限信息" />
          <el-step title="检查并完成" />
        </el-steps>
      </div>
      <div v-show="activeStep === 1" class="form-container">
        <div class="title">角色信息</div>
        <div class="form">
          <el-form ref="roleFormRef" class="form-box" :model="roleForm" :rules="roleRules">
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="roleForm.roleName" />
            </el-form-item>
            <el-form-item label="角色描述" prop="remark">
              <el-input v-model="roleForm.remark" type="textarea" />
            </el-form-item>
          </el-form>
        </div>
      </div>
      <!-- v-show 只是 display 的显示隐藏(保留子组件状态)，并不会像 v-if 销毁(子组件状态销毁) -->
      <div v-show="activeStep === 2" class="form-container">
        <div class="title">权限配置</div>
        <div class="form">
          <div class="tree-wrapper">
            <div v-for="(item, index) in treeList" :key="item.id" class="tree-item">
              <div class="tree-title">{{ item.title }}</div>
              <el-tree 
                :data="item.children" 
                show-checkbox 
                default-expand-all 
                node-key="id"
                :props="{ label: 'title' }" 
                ref="treeRefs"
                :default-checked-keys="roleForm.perms[index]"
              />
            </div>
          </div>
        </div>
      </div>
      <div v-show="activeStep === 3" class="form-container">
        <div class="title">检查并完成</div>
        <div class="form">
          <div class="info">
            <div class="form-item">角色名称：{{ roleForm.roleName }}</div>
            <div class="form-item">角色描述：{{ roleForm.remark }}</div>
            <div class="form-item">角色权限：</div>
            <div class="tree-wrapper">
              <div v-for="(item, index) in treeList" :key="item.id" class="tree-item">
                <div class="tree-title">{{ item.title }}</div>
                <el-tree
                  :data="item.children"
                  show-checkbox
                  default-expand-all
                  node-key="id"
                  :props="{ label: 'title', disabled: () => true }"
                  ref="diabledTreeRefs"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button v-if="activeStep > 1" @click="prevStep()">上一步</el-button>
        <el-button v-if="activeStep < 3" @click="nextStep()" type="primary">下一步</el-button>
        <el-button v-if="activeStep === 3" @click="onSubmit()" type="primary">
          {{ $route.params.id ? '确认更新' : '确认添加' }}
        </el-button>
      </div>
    </footer>
  </div>
</template>


<style scoped lang="scss">
.add-role {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }

      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    position: fixed;
    top: 64px;
    bottom: 88px;
    width: 100%;
    overflow-y: auto;
    background: #f4f6f8;
    padding: 20px 30px;
    display: flex;

    .step-container {
      height: 400px;
      width: 200px;
    }

    .form-container {
      flex: 1;
      background-color: #fff;
      overflow-y: auto;

      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }

      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;

        .el-form {
          display: flex;
          flex-wrap: wrap;
        }

        .info {
          font-size: 14px;
          color: #666;

          .form-item {
            margin-bottom: 20px;
          }
        }
      }

      .form-box {
        width: 600px;
        display: flex;
        flex-direction: column;
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
    z-index: 10001;
  }

  .tree-wrapper {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;

    .tree-item {
      flex: 1;
      padding: 0px 4px;
      text-align: center;

      .tree-title {
        background: #f5f7fa;
        text-align: center;
        padding: 10px 0;
        margin-bottom: 12px;
      }
    }
  }
}
</style>